import { resolveSchemaToProps, schemaMap, schemaResolverMap } from './schema-resolver';
import { DynamicResolver, MapperFunction, SchemaResolverFunction } from './types';

export function createPropsResolver<T extends Record<string, any>>(
    componentPropsObject: T,
    defaultSchema: Record<string, any>,
    schemaMapper: Map<string, string | MapperFunction> = new Map(),
    schemaResolver: SchemaResolverFunction = (
        dynamicResolver: DynamicResolver,
        schema: Record<string,any>,
        resolveContext: Record<string, any>
    ) => schema
) {
    schemaMap[defaultSchema.title] = defaultSchema;
    schemaResolverMap[defaultSchema.title] = schemaResolver;
    return (schemaValue: Record<string, any>) => {
        const resolvedPropsValue = resolveSchemaToProps(schemaValue, defaultSchema, schemaMapper);
        const defaultProps = Object.keys(componentPropsObject).reduce((propsObject: Record<string, any>, propKey: string) => {
            propsObject[propKey] = componentPropsObject[propKey].default;
            return propsObject;
        }, {});

        return Object.assign(defaultProps, resolvedPropsValue);
    };
}
